package cn.net.dpi.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;

/**
 * Copyright(c) 2021 Dayou Positioning Intelligence Co.,Ltd
 * All rights reserved.
 *
 * @Date 2022/1/13
 * @Author changguoshan (changguoshan@dayoupi.cn)
 * @Version 0.2
 * @Reviewer
 */
public class RandomUtil {
    private static final String[] GENERATE_SOURCE = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};
    private static final int STR_LEN = GENERATE_SOURCE.length;
    private static final int RANDOM_NUM = 90;
    private static final int RUNDOM_START = 10;
    private static final String SDK_SERVER_NAME = "dysdk";


    /***
     * 生成长度为10的随机字符串
     *
     * @return 长度为10的随机字符串
     */
    public static String getRandom() {
        StringBuffer stringBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int num = Integer.parseInt(str, 16);
            stringBuffer.append(GENERATE_SOURCE[num % STR_LEN]);
        }
        int random = (int) (Math.random() * RANDOM_NUM) + RUNDOM_START;
        stringBuffer.append(random);
        return stringBuffer.toString();
    }

    /**
     *  根据传入的sdkId生成sdk鉴权码
     * @param sdkId sdkId
     * @return sdk鉴权码
     */
    public static String getSdkSecret(String sdkId) {
        try {
            String[] array = new String[]{sdkId, SDK_SERVER_NAME};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString().substring(0,16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
